﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Resources;
using System.Windows.Forms;
using Foundation;
using ICSharpCode.AvalonEdit.Highlighting;
using Poet.Properties;

namespace Poet.Modules
{
    /// <summary>
    /// HighlightingHelper.
    /// </summary>
    public class SyntaxModule
    {
        public const string DefaultExtensionOfHighlightingFiles = ".xshd";

        /// <summary>
        /// Loads the default palettes.
        /// </summary>
        public static void LoadDefaultPalettes()
        {
            try
            {
                CreateDefaultSyntaxPalettes();
                var fileNames = PathProvider.GetFileListByExtension(DefaultExtensionOfHighlightingFiles);
                fileNames.Sort();

                for (var i = 0; i < 7; i++)
                {
                    var complexPalettes = new List<string>();
                    foreach (var fileName in fileNames)
                    {
                        try
                        {
                            HighlightingManager.Instance.RegisterHighlighting(fileName);
                        }
                        catch (Exception)
                        {
                            complexPalettes.Add(fileName);
                        }
                    }

                    if (complexPalettes.Count == 0) break;
                    fileNames = complexPalettes;
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private static void CreateDefaultSyntaxPalettes()
        {
            var resourceManager = new ResourceManager(typeof(Data.SyntaxPalettes));
            var items = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true).Cast<DictionaryEntry>().ToList();
            foreach (var item in items)
            {
                var name = item.Key + ".xshd";
                if (PathProvider.Exists(name)) continue;
                var path = PathProvider.FindFileByName(Settings.Default.SyntaxPalettes + name);
                File.WriteAllBytes(path, (byte[])item.Value);
            }
        }
    }
}
